package org.example.classtopia.Service.Impl;

import org.example.classtopia.Model.Entity.Curriculum;
import org.example.classtopia.Model.Entity.Course;
import org.example.classtopia.Repository.CurriculumRepository;
import org.example.classtopia.Service.CourseService;
import org.example.classtopia.Service.CurriculumSyncService;
import org.example.classtopia.Utils.CurriculumToCourseConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.example.classtopia.Utils.CurriculumToCourseConverter.add45Minutes;

@Service
public class CurriculumSyncServiceImpl implements CurriculumSyncService {

    @Autowired
    private CurriculumRepository curriculumRepository;

    @Autowired
    private CourseService courseService;


    // 学期开始日期，可以通过配置注入，示例为硬编码
    private static final String CURRENT_SEMESTER = "2025-06-23";

    @Override
    @Transactional
    public void syncCurriculumToCourse(Long userId) {
        // 1. 查询该用户的所有爬取课程
        List<Curriculum> curriculumList = curriculumRepository.findByUserId(userId);

        for (Curriculum curr : curriculumList) {
            // 2. 查找冲突课程 (这里只写示例，需按实际情况实现冲突搜索)
            String startTime = convertClassToTime(curr.getFromClass());
            String endClassStart = convertClassToTime(curr.getEndClass());
            String endTime = add45Minutes(endClassStart);

            List<Course> conflicts = courseService.findConflicts(
                    userId,
                    curr.getFromWeek(),
                    curr.getEndWeek(),
                    curr.getDay(),
                    startTime,
                    endTime
            );
            // 3. 删除冲突课程
            for (Course conflictCourse : conflicts) {
                courseService.deleteCourseById(conflictCourse.getId());
            }

            // 4. 转换并新增课程
            Course courseToInsert = CurriculumToCourseConverter.convert(curr, CURRENT_SEMESTER);
            courseService.createCourse(courseToInsert);
        }
    }

    public String convertClassToTime(Integer classNumber) {
        // TODO: 实现节次转时间段字符串 (如第1节 => "08:00", 第2节 => "08:45" 等)，这里演示返回固定字符串
        // 你需要根据学校课表时间实现精确映射
        return CurriculumToCourseConverter.classToTime(classNumber);

    }
}

